package top.lshaci.learning.jsoup;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.util.concurrent.TimeUnit;

/**
 * Jiaoxi
 *
 * @author liangxu
 */
public class Jiaoxi {

    static String dir = "D:\\Jiaoxi";

    static String albumUrl = "https://www.51jiaoxi.com/album-{}.html";

    static String previewUrl = "https://www.51jiaoxi.com/api/document/preview?document_id={}&all=1";

    static String fileUrlPrefix = "https://img-preview.51jiaoxi.com/1/3/";

    public static void main(String[] args) throws Exception {
        String albumId = "4713";
        albumDownload(albumId);
    }

    /**
     * 专辑下载
     *
     * @param albumId 专辑id
     * @throws Exception
     */
    private static void albumDownload(String albumId) throws Exception {
        Document document = Jsoup.connect(StrUtil.format(albumUrl, albumId)).get();
        Elements elements = document.select("div.doc-preview[data-id]");
        for (Element element : elements) {
            String documentId = element.attr("data-id");
            previewDownload(documentId);
        }
    }

    /**
     * 预览下载
     *
     * @param documentId 文档id
     * @throws Exception
     */
    public static void previewDownload(String documentId) throws Exception {
        String respBody = HttpUtil.get(StrUtil.format(previewUrl, documentId));
        JSONObject data = JSON.parseObject(respBody).getJSONArray("data").getJSONObject(0);
        JSONObject formatSubset = data.getJSONArray("format_subsets").getJSONObject(0);
        String title = formatSubset.getString("title");
        String dirPath = dir + "\\" + title.split("\\.")[0];
        mkdir(dirPath);
        JSONArray previewFiles = formatSubset.getJSONArray("preview_files");
        for (int i = 0; i < previewFiles.size(); i++) {
            String fileUrl = previewFiles.getJSONObject(i).getString("file_url");
            String fileName = FileNameUtil.getName(fileUrl);
            download(fileUrlPrefix + fileUrl, dirPath, fileName);
        }
    }

    /**
     * 下载
     *
     * @param fileUrl  文件url
     * @param dirPath  目录
     * @param fileName 文件名
     * @throws Exception
     */
    private static void download(String fileUrl, String dirPath, String fileName) throws Exception {
        System.err.println("保存图片: " + fileUrl);
        FileOutputStream out = new FileOutputStream(dirPath + "\\" + fileName);
        HttpUtil.download(fileUrl, out, true);
        TimeUnit.MILLISECONDS.sleep(500);
    }

    private static void mkdir(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }
}
